package com.wondertek.onvif.controller;

import cn.hutool.core.util.StrUtil;
import com.wondertek.onvif.common.ResultBean;
import com.wondertek.onvif.dto.AddDeviceByIpRequest;
import com.wondertek.onvif.dto.BatchAddDevicesRequest;
import com.wondertek.onvif.dto.BatchAddDevicesResponse;
import com.wondertek.onvif.entity.OnvifDevice;
import com.wondertek.onvif.service.OnvifDeviceService;
import com.wondertek.onvif.service.OnvifDiscoveryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * ONVIF设备管理控制器
 * 
 * @author wondertek
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/onvif/devices")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class OnvifDeviceController {

    private static final Logger log = LoggerFactory.getLogger(OnvifDeviceController.class);
    
    private final OnvifDeviceService deviceService;
    private final OnvifDiscoveryService discoveryService;

    /**
     * 获取设备列表
     * 
     * @param page 页码
     * @param size 页大小
     * @param sort 排序字段
     * @param keyword 搜索关键字
     * @return 设备列表
     */
    @GetMapping
    public ResultBean<Page<OnvifDevice>> getDevices(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sort,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String manufacturer,
            @RequestParam(required = false) Boolean enabled,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortOrder) {
        try {
            // 使用search参数作为主要搜索关键字，如果没有则使用keyword
            String searchKeyword = StrUtil.isNotEmpty(search) ? search.trim() : 
                                  (StrUtil.isNotEmpty(keyword) ? keyword.trim() : null);
            
            // 构建排序条件
            Sort sortCondition;
            if (StrUtil.isNotEmpty(sortField)) {
                Sort.Direction direction = "desc".equalsIgnoreCase(sortOrder) ? 
                    Sort.Direction.DESC : Sort.Direction.ASC;
                sortCondition = Sort.by(direction, sortField);
            } else {
                sortCondition = Sort.by(sort);
            }
            
            // 前端传递的page是1-based，但PageRequest.of()需要0-based，所以需要减1
            int pageIndex = Math.max(0, page - 1);
            log.info("分页参数转换 - 前端page: {}, 后端pageIndex: {}, size: {}", page, pageIndex, size);
            
            Pageable pageable = PageRequest.of(pageIndex, size, sortCondition);
            
            // 调用service层的高级查询方法
            Page<OnvifDevice> devices = deviceService.getDevicesWithFilters(
                pageable, searchKeyword, status, manufacturer, enabled);
            
            return ResultBean.success(devices, "获取设备列表成功");
        } catch (Exception e) {
            log.error("获取设备列表失败", e);
            return ResultBean.error("获取设备列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有设备（不分页）
     * 
     * @return 所有设备列表
     */
    @GetMapping("/all")
    public ResultBean<List<OnvifDevice>> getAllDevices() {
        try {
            List<OnvifDevice> devices = deviceService.getAllDevices();
            return ResultBean.success(devices, "获取所有设备成功");
        } catch (Exception e) {
            log.error("获取所有设备失败", e);
            return ResultBean.error("获取所有设备失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取设备
     * 
     * @param id 设备ID
     * @return 设备信息
     */
    @GetMapping("/{id}")
    public ResultBean<OnvifDevice> getDevice(@PathVariable Long id) {
        try {
            return deviceService.getDeviceById(id)
                .map(device -> ResultBean.success(device, "获取设备信息成功"))
                .orElse(ResultBean.notFound("设备不存在"));
        } catch (Exception e) {
            log.error("获取设备信息失败", e);
            return ResultBean.error("获取设备信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据设备ID获取设备信息
     * 
     * @param deviceId 设备ID
     * @return 设备信息
     */
    @GetMapping("/device-id/{deviceId}")
    public ResultBean<OnvifDevice> getDeviceByDeviceId(@PathVariable String deviceId) {
        try {
            return deviceService.getDeviceByDeviceId(deviceId)
                .map(device -> ResultBean.success(device, "获取设备信息成功"))
                .orElse(ResultBean.notFound("设备不存在"));
        } catch (Exception e) {
            log.error("根据设备ID获取设备信息失败", e);
            return ResultBean.error("获取设备信息失败: " + e.getMessage());
        }
    }

    /**
     * 添加设备
     * 
     * @param device 设备信息
     * @return 添加的设备
     */
    @PostMapping
    public ResultBean<OnvifDevice> addDevice(@Valid @RequestBody OnvifDevice device) {
        try {
            OnvifDevice savedDevice = deviceService.addDevice(device);
            return ResultBean.success(savedDevice, "添加设备成功");
        } catch (Exception e) {
            log.error("添加设备失败", e);
            return ResultBean.error("添加设备失败: " + e.getMessage());
        }
    }

    /**
     * 根据IP地址、用户名和密码添加设备
     * 
     * @param request 添加设备请求
     * @return 添加的设备
     */
    @PostMapping("/add-by-ip")
    public ResultBean<OnvifDevice> addDeviceByIp(@Valid @RequestBody AddDeviceByIpRequest request) {
        try {
            // 检查设备是否已存在
            Optional<OnvifDevice> existingDevice = deviceService.findByIpAddressAndPort(
                request.getIpAddress(), request.getPort());
            
            OnvifDevice device = deviceService.addDeviceByIp(request);
            
            if (existingDevice.isPresent()) {
                return ResultBean.success(device, "设备已存在，已更新设备认证信息");
            } else {
                return ResultBean.success(device, "设备添加成功");
            }
        } catch (Exception e) {
            log.error("根据IP添加设备失败", e);
            return ResultBean.error("添加设备失败: " + e.getMessage());
        }
    }

    /**
     * 批量添加设备
     * 
     * @param request 批量添加设备请求
     * @return 批量添加结果
     */
    @PostMapping("/batch-add")
    public ResultBean<BatchAddDevicesResponse> batchAddDevices(@Valid @RequestBody BatchAddDevicesRequest request) {
        try {
            BatchAddDevicesResponse response = deviceService.batchAddDevices(request);
            
            String message;
            if (response.getFailureCount() == 0) {
                // 全部成功 - 返回200
                message = String.format("批量添加设备成功，共添加 %d 个设备", response.getSuccessCount());
                return ResultBean.success(response, message);
            } else if (response.getSuccessCount() == 0) {
                // 全部失败 - 返回400
                message = String.format("批量添加设备失败，%d 个设备添加失败", response.getFailureCount());
                return ResultBean.error(400, message, response);
            } else {
                // 部分成功 - 返回206 (Partial Content)
                message = String.format("批量添加设备完成，成功 %d 个，失败 %d 个", 
                    response.getSuccessCount(), response.getFailureCount());
                return ResultBean.error(206, message, response);
            }
        } catch (Exception e) {
            log.error("批量添加设备失败", e);
            return ResultBean.serverError("批量添加设备失败: " + e.getMessage());
        }
    }

    /**
     * 更新设备
     * 
     * @param id 设备ID
     * @param device 设备信息
     * @return 更新的设备
     */
    @PutMapping("/{id}")
    public ResultBean<OnvifDevice> updateDevice(@PathVariable Long id, @Valid @RequestBody OnvifDevice device) {
        try {
            OnvifDevice updatedDevice = deviceService.updateDevice(id, device);
            return ResultBean.success(updatedDevice, "更新设备成功");
        } catch (Exception e) {
            log.error("更新设备失败", e);
            return ResultBean.error("更新设备失败: " + e.getMessage());
        }
    }

    /**
     * 删除设备
     * 
     * @param id 设备ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResultBean<Void> deleteDevice(@PathVariable Long id) {
        try {
            deviceService.deleteDevice(id);
            return ResultBean.success("删除设备成功");
        } catch (Exception e) {
            log.error("删除设备失败", e);
            return ResultBean.error("删除设备失败: " + e.getMessage());
        }
    }

    /**
     * 启用/禁用设备
     * 
     * @param id 设备ID
     * @param enabled 是否启用
     * @return 更新的设备
     */
    @PatchMapping("/{id}/enabled")
    public ResultBean<OnvifDevice> toggleDeviceEnabled(@PathVariable Long id, @RequestBody Map<String, Boolean> request) {
        try {
            Boolean enabled = request.get("enabled");
            if (enabled == null) {
                return ResultBean.badRequest("缺少enabled参数");
            }
            OnvifDevice device = deviceService.toggleDeviceEnabled(id, enabled);
            String message = enabled ? "启用设备成功" : "禁用设备成功";
            return ResultBean.success(device, message);
        } catch (Exception e) {
            log.error("切换设备状态失败", e);
            return ResultBean.error("切换设备状态失败: " + e.getMessage());
        }
    }

    /**
     * 测试设备连接
     * 
     * @param id 设备ID
     * @return 连接测试结果
     */
    @PostMapping("/{id}/test")
    public ResultBean<Map<String, Object>> testDeviceConnection(@PathVariable Long id) {
        try {
            boolean connected = deviceService.testDeviceConnection(id);
            Map<String, Object> result = Map.of(
                "success", connected,
                "message", connected ? "连接成功" : "连接失败"
            );
            return ResultBean.success(result, connected ? "设备连接测试成功" : "设备连接测试失败");
        } catch (Exception e) {
            log.error("测试设备连接失败", e);
            Map<String, Object> result = Map.of(
                "success", false,
                "message", "连接测试失败: " + e.getMessage()
            );
            return ResultBean.error("连接测试失败: " + e.getMessage());
        }
    }

    /**
     * 刷新设备信息
     * 
     * @param id 设备ID
     * @return 刷新后的设备信息
     */
    @PostMapping("/{id}/refresh")
    public ResultBean<OnvifDevice> refreshDeviceInfo(@PathVariable Long id) {
        try {
            OnvifDevice device = deviceService.refreshDeviceInfo(id);
            return ResultBean.success(device, "刷新设备信息成功");
        } catch (Exception e) {
            log.error("刷新设备信息失败", e);
            return ResultBean.error("刷新设备信息失败: " + e.getMessage());
        }
    }

    /**
     * 发现局域网设备
     * 
     * @return 发现的设备列表
     */
    @PostMapping("/discover")
    public ResultBean<List<OnvifDiscoveryService.DiscoveredDevice>> discoverDevices() {
        try {
            List<OnvifDiscoveryService.DiscoveredDevice> devices = discoveryService.discoverDevices();
            return ResultBean.success(devices, "设备发现完成，找到 " + devices.size() + " 个设备");
        } catch (Exception e) {
            log.error("设备发现失败", e);
            return ResultBean.error("设备发现失败: " + e.getMessage());
        }
    }

    /**
     * 根据发现的设备信息添加设备
     * 
     * @param discoveredDevice 发现的设备信息
     * @return 添加的设备
     */
    @PostMapping("/add-discovered")
    public ResultBean<OnvifDevice> addDiscoveredDevice(@RequestBody com.wondertek.onvif.dto.AddDiscoveredDeviceRequest request) {
        try {
            OnvifDevice device = new OnvifDevice();
            
            // 检查是否有完整的discoveredDevice对象
            OnvifDiscoveryService.DiscoveredDevice discoveredDevice = request.getDiscoveredDevice();
            
            if (discoveredDevice != null) {
                // 使用完整的discoveredDevice对象
                String deviceName = request.getCustomName();
                if (StrUtil.isEmpty(deviceName)) {
                    deviceName = discoveredDevice.getManufacturer() + " " + discoveredDevice.getModel();
                }
                device.setName(deviceName);
                
                device.setIpAddress(discoveredDevice.getIpAddress());
                
                // 从发现的设备信息中提取ONVIF端口
                Integer onvifPort = extractOnvifPortFromXAddrs(discoveredDevice.getXAddrs());
                device.setPort(onvifPort != null ? onvifPort : 80);
                
                device.setManufacturer(discoveredDevice.getManufacturer());
                device.setModel(discoveredDevice.getModel());
            } else {
                // 使用简化的设备信息（兼容前端直接发送的数据）
                device.setName(request.getName() != null ? request.getName() : "Unknown Device");
                device.setIpAddress(request.getIpAddress());
                device.setPort(request.getPort() != null ? request.getPort() : 80);
                device.setManufacturer(request.getManufacturer());
                device.setModel(request.getModel());
            }
            
            // 设置认证信息
            device.setUsername(request.getUsername());
            device.setPassword(request.getPassword());
            
            // 设置描述
            String description = request.getDescription();
            if (StrUtil.isEmpty(description)) {
                description = "通过设备发现添加";
            }
            device.setDescription(description);
            
            // 从XAddrs中提取服务地址
            if (discoveredDevice != null && StrUtil.isNotEmpty(discoveredDevice.getXAddrs())) {
                device.setServiceUrl(discoveredDevice.getXAddrs());
            }
            
            OnvifDevice savedDevice = deviceService.addDevice(device);
            return ResultBean.success(savedDevice, "添加发现的设备成功，正在获取通道信息...");
        } catch (Exception e) {
            log.error("添加发现的设备失败", e);
            return ResultBean.error("添加发现的设备失败: " + e.getMessage());
        }
    }
    
    /**
     * 从XAddrs中提取ONVIF端口
     * 
     * @param xAddrs XAddrs字符串
     * @return 端口号，如果提取失败返回null
     */
    private Integer extractOnvifPortFromXAddrs(String xAddrs) {
        if (StrUtil.isEmpty(xAddrs)) {
            return null;
        }
        
        try {
            // 解析XAddrs中的端口信息
            // 格式通常为: http://192.168.1.100:8080/onvif/device_service
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("http://[^:]+:(\\d+)");
            java.util.regex.Matcher matcher = pattern.matcher(xAddrs);
            if (matcher.find()) {
                int port = Integer.parseInt(matcher.group(1));
                log.debug("从XAddrs中提取到端口: {}", port);
                return port;
            }
        } catch (Exception e) {
            log.warn("解析XAddrs端口失败: {}", xAddrs, e);
        }
        
        return null;
    }

    /**
     * 获取设备统计信息
     * 
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public ResultBean<OnvifDeviceService.DeviceStatistics> getDeviceStatistics() {
        try {
            OnvifDeviceService.DeviceStatistics statistics = deviceService.getDeviceStatistics();
            return ResultBean.success(statistics, "获取设备统计信息成功");
        } catch (Exception e) {
            log.error("获取设备统计信息失败", e);
            return ResultBean.error("获取设备统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据状态获取设备列表
     * 
     * @param status 设备状态
     * @return 设备列表
     */
    @GetMapping("/by-status/{status}")
    public ResultBean<List<OnvifDevice>> getDevicesByStatus(@PathVariable String status) {
        try {
            OnvifDevice.DeviceStatus deviceStatus = OnvifDevice.DeviceStatus.valueOf(status.toUpperCase());
            List<OnvifDevice> devices = deviceService.getDevicesByStatus(deviceStatus);
            return ResultBean.success(devices, "获取" + status + "状态设备列表成功");
        } catch (IllegalArgumentException e) {
            return ResultBean.badRequest("无效的设备状态: " + status);
        } catch (Exception e) {
            log.error("根据状态获取设备列表失败", e);
            return ResultBean.error("根据状态获取设备列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取启用的设备列表
     * 
     * @return 启用的设备列表
     */
    @GetMapping("/enabled")
    public ResultBean<List<OnvifDevice>> getEnabledDevices() {
        try {
            List<OnvifDevice> devices = deviceService.getEnabledDevices();
            return ResultBean.success(devices, "获取启用设备列表成功");
        } catch (Exception e) {
            log.error("获取启用设备列表失败", e);
            return ResultBean.error("获取启用设备列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备列表（用于下拉选择）
     * 
     * @return 设备列表
     */
    @GetMapping("/list")
    public ResultBean<List<OnvifDevice>> getDeviceList() {
        try {
            List<OnvifDevice> devices = deviceService.getAllDevices();
            return ResultBean.success(devices, "获取设备列表成功");
        } catch (Exception e) {
            log.error("获取设备列表失败", e);
            return ResultBean.error("获取设备列表失败: " + e.getMessage());
        }
    }

    /**
     * 同步设备时间
     * 
     * @param id 设备ID
     * @return 同步结果
     */
    @PostMapping("/{id}/sync-time")
    public ResultBean<Map<String, Object>> syncDeviceTime(@PathVariable Long id) {
        try {
            Map<String, Object> result = deviceService.syncDeviceTime(id);
            return ResultBean.success(result, "设备时间同步成功");
        } catch (Exception e) {
            log.error("同步设备时间失败", e);
            return ResultBean.error("同步设备时间失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备网络配置
     * 
     * @param id 设备ID
     * @return 网络配置
     */
    @GetMapping("/{id}/network")
    public ResultBean<Map<String, Object>> getDeviceNetworkConfig(@PathVariable Long id) {
        try {
            Map<String, Object> config = deviceService.getDeviceNetworkConfig(id);
            return ResultBean.success(config, "获取设备网络配置成功");
        } catch (Exception e) {
            log.error("获取设备网络配置失败", e);
            return ResultBean.error("获取设备网络配置失败: " + e.getMessage());
        }
    }

    /**
     * 更新设备网络配置
     * 
     * @param id 设备ID
     * @param config 网络配置
     * @return 更新结果
     */
    @PutMapping("/{id}/network")
    public ResultBean<Map<String, Object>> updateDeviceNetworkConfig(@PathVariable Long id, @RequestBody Map<String, Object> config) {
        try {
            Map<String, Object> result = deviceService.updateDeviceNetworkConfig(id, config);
            return ResultBean.success(result, "更新设备网络配置成功");
        } catch (Exception e) {
            log.error("更新设备网络配置失败", e);
            return ResultBean.error("更新设备网络配置失败: " + e.getMessage());
        }
    }

    /**
     * 重启设备
     * 
     * @param id 设备ID
     * @return 重启结果
     */
    @PostMapping("/{id}/reboot")
    public ResultBean<Map<String, Object>> rebootDevice(@PathVariable Long id) {
        try {
            Map<String, Object> result = deviceService.rebootDevice(id);
            return ResultBean.success(result, "设备重启命令发送成功");
        } catch (Exception e) {
            log.error("重启设备失败", e);
            return ResultBean.error("重启设备失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备能力集
     * 
     * @param id 设备ID
     * @return 设备能力集
     */
    @GetMapping("/{id}/capabilities")
    public ResultBean<Map<String, Object>> getDeviceCapabilities(@PathVariable Long id) {
        try {
            Map<String, Object> capabilities = deviceService.getDeviceCapabilities(id);
            return ResultBean.success(capabilities, "获取设备能力集成功");
        } catch (Exception e) {
            log.error("获取设备能力集失败", e);
            return ResultBean.error("获取设备能力集失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备性能指标
     * 
     * @param id 设备ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param interval 时间间隔
     * @return 性能指标
     */
    @GetMapping("/{id}/metrics")
    public ResultBean<Map<String, Object>> getDeviceMetrics(
            @PathVariable Long id,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String interval) {
        try {
            Map<String, Object> metrics = deviceService.getDeviceMetrics(id, startTime, endTime, interval);
            return ResultBean.success(metrics, "获取设备性能指标成功");
        } catch (Exception e) {
            log.error("获取设备性能指标失败", e);
            return ResultBean.error("获取设备性能指标失败: " + e.getMessage());
        }
    }

    /**
     * 验证设备连接
     * 
     * @param deviceInfo 设备信息
     * @return 验证结果
     */
    @PostMapping("/discovery/validate")
    public ResultBean<Map<String, Object>> validateDevice(@RequestBody Map<String, Object> deviceInfo) {
        try {
            String ipAddress = (String) deviceInfo.get("ipAddress");
            Integer port = (Integer) deviceInfo.get("port");
            String username = (String) deviceInfo.get("username");
            String password = (String) deviceInfo.get("password");
            
            if (port == null) {
                port = 80; // 默认端口
            }
            
            // 创建临时设备对象进行验证
            OnvifDevice tempDevice = new OnvifDevice();
            tempDevice.setIpAddress(ipAddress);
            tempDevice.setPort(port);
            tempDevice.setUsername(username);
            tempDevice.setPassword(password);
            
            // 测试设备连接
            boolean isConnected = deviceService.testDeviceConnection(tempDevice);
            
            Map<String, Object> result = Map.of(
                "connected", isConnected,
                "success", isConnected,
                "message", isConnected ? "设备连接成功" : "设备连接失败",
                "ipAddress", ipAddress,
                "port", port
            );
            
            return ResultBean.success(result, isConnected ? "设备验证成功" : "设备验证失败");
        } catch (Exception e) {
            log.error("设备验证失败", e);
            return ResultBean.error("设备验证失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除设备
     * 
     * @param request 批量删除请求
     * @return 删除结果
     */
    @PostMapping("/batch/delete")
    public ResultBean<Map<String, Object>> batchDeleteDevices(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Object> deviceIdObjects = (List<Object>) request.get("deviceIds");
            
            if (deviceIdObjects == null || deviceIdObjects.isEmpty()) {
                return ResultBean.error("设备ID列表不能为空");
            }
            
            // 将Object转换为Long，处理Integer和Long的兼容性问题
            List<Long> deviceIds = new ArrayList<>();
            for (Object idObj : deviceIdObjects) {
                if (idObj instanceof Integer) {
                    deviceIds.add(((Integer) idObj).longValue());
                } else if (idObj instanceof Long) {
                    deviceIds.add((Long) idObj);
                } else if (idObj instanceof String) {
                    try {
                        deviceIds.add(Long.parseLong((String) idObj));
                    } catch (NumberFormatException e) {
                        return ResultBean.error("无效的设备ID格式: " + idObj);
                    }
                } else {
                    return ResultBean.error("不支持的设备ID类型: " + idObj.getClass().getSimpleName());
                }
            }
            
            int successCount = 0;
            int failureCount = 0;
            List<String> failureMessages = new ArrayList<>();
            
            for (Long deviceId : deviceIds) {
                try {
                    deviceService.deleteDevice(deviceId);
                    successCount++;
                    log.info("成功删除设备: {}", deviceId);
                } catch (Exception e) {
                    failureCount++;
                    String errorMsg = "删除设备 " + deviceId + " 失败: " + e.getMessage();
                    failureMessages.add(errorMsg);
                    log.error(errorMsg, e);
                }
            }
            
            Map<String, Object> result = Map.of(
                "totalCount", deviceIds.size(),
                "successCount", successCount,
                "failureCount", failureCount,
                "failureMessages", failureMessages
            );
            
            String message;
            if (failureCount == 0) {
                message = String.format("批量删除设备成功，共删除 %d 个设备", successCount);
            } else if (successCount == 0) {
                message = String.format("批量删除设备失败，%d 个设备删除失败", failureCount);
            } else {
                message = String.format("批量删除设备完成，成功 %d 个，失败 %d 个", successCount, failureCount);
            }
            
            return ResultBean.success(result, message);
        } catch (Exception e) {
            log.error("批量删除设备失败", e);
            return ResultBean.error("批量删除设备失败: " + e.getMessage());
        }
    }

    /**
     * 批量操作设备
     * 
     * @param request 批量操作请求
     * @return 操作结果
     */
    @PostMapping("/batch")
    public ResultBean<Map<String, Object>> batchOperateDevices(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Object> deviceIdObjects = (List<Object>) request.get("ids");
            String action = (String) request.get("action");
            
            if (deviceIdObjects == null || deviceIdObjects.isEmpty()) {
                return ResultBean.error("设备ID列表不能为空");
            }
            
            if (action == null || action.trim().isEmpty()) {
                return ResultBean.error("操作类型不能为空");
            }
            
            // 将Object转换为Long，处理Integer和Long的兼容性问题
            List<Long> deviceIds = new ArrayList<>();
            for (Object idObj : deviceIdObjects) {
                if (idObj instanceof Integer) {
                    deviceIds.add(((Integer) idObj).longValue());
                } else if (idObj instanceof Long) {
                    deviceIds.add((Long) idObj);
                } else if (idObj instanceof String) {
                    try {
                        deviceIds.add(Long.parseLong((String) idObj));
                    } catch (NumberFormatException e) {
                        return ResultBean.error("无效的设备ID格式: " + idObj);
                    }
                } else {
                    return ResultBean.error("不支持的设备ID类型: " + idObj.getClass().getSimpleName());
                }
            }
            
            int successCount = 0;
            int failureCount = 0;
            List<String> failureMessages = new ArrayList<>();
            
            for (Long deviceId : deviceIds) {
                try {
                    switch (action.toLowerCase()) {
                        case "enable":
                            deviceService.toggleDeviceEnabled(deviceId, true);
                            break;
                        case "disable":
                            deviceService.toggleDeviceEnabled(deviceId, false);
                            break;
                        case "delete":
                            deviceService.deleteDevice(deviceId);
                            break;
                        case "refresh":
                            deviceService.refreshDeviceInfo(deviceId);
                            break;
                        default:
                            throw new IllegalArgumentException("不支持的操作类型: " + action);
                    }
                    successCount++;
                    log.info("成功{}设备: {}", action, deviceId);
                } catch (Exception e) {
                    failureCount++;
                    String errorMsg = action + "设备 " + deviceId + " 失败: " + e.getMessage();
                    failureMessages.add(errorMsg);
                    log.error(errorMsg, e);
                }
            }
            
            Map<String, Object> result = Map.of(
                "totalCount", deviceIds.size(),
                "successCount", successCount,
                "failureCount", failureCount,
                "failureMessages", failureMessages,
                "action", action
            );
            
            String actionName = getActionName(action);
            String message;
            if (failureCount == 0) {
                message = String.format("批量%s设备成功，共处理 %d 个设备", actionName, successCount);
            } else if (successCount == 0) {
                message = String.format("批量%s设备失败，%d 个设备处理失败", actionName, failureCount);
            } else {
                message = String.format("批量%s设备完成，成功 %d 个，失败 %d 个", actionName, successCount, failureCount);
            }
            
            return ResultBean.success(result, message);
        } catch (Exception e) {
            log.error("批量操作设备失败", e);
            return ResultBean.error("批量操作设备失败: " + e.getMessage());
        }
    }
    
    private String getActionName(String action) {
        switch (action.toLowerCase()) {
            case "enable": return "启用";
            case "disable": return "禁用";
            case "delete": return "删除";
            case "refresh": return "刷新";
            default: return action;
        }
    }
}